package com.git.auth.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.git.auth.entity.AuthorityEntity;
import com.git.auth.entity.CredentialsAuthoritiesEntity;
import com.git.auth.entity.CredentialsEntity;
import com.git.auth.mapper.AuthorityMapper;
import com.git.auth.mapper.CredentialsAuthoritiesMapper;
import com.git.auth.mapper.CredentialsMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.security.core.userdetails.User;
import java.util.ArrayList;
import java.util.List;

/**
 * 此例子演示的是用户权限信息在权限服务所在的数据库，所以直接通过MAPPER查询。
 * 但实际情况下，用户信息可能划分在系统模块所以可以考虑用feign调用其他模块以获取用户信息
 * @author huangzhiyu
 */
@Slf4j
@Component(value = "sebUserDetailsService")
public class SebUserDetailsService implements UserDetailsService {

    @Autowired
    CredentialsMapper credentialsMapper;

    @Autowired
    CredentialsAuthoritiesMapper credentialsAuthoritiesMapper;

    @Autowired
    AuthorityMapper authorityMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CredentialsEntity credentialsEntityQuery = new CredentialsEntity();
        credentialsEntityQuery.setName(username);
        List<CredentialsEntity> credentialsEntityList = credentialsMapper.selectList(new QueryWrapper<>(credentialsEntityQuery));
        if(CollectionUtils.isEmpty(credentialsEntityList)){
            throw new UsernameNotFoundException("获取["+username+"]用户信息失败：查询无记录");
        }
        if(credentialsEntityList.size() > 1){
            throw new UsernameNotFoundException("获取["+username+"]用户信息失败：数据异常");
        }
        CredentialsEntity credentialsEntity = credentialsEntityList.get(0);
        CredentialsAuthoritiesEntity credentialsAuthoritiesEntityQuery = new CredentialsAuthoritiesEntity();
        credentialsAuthoritiesEntityQuery.setCredentialsId(credentialsEntity.getId());
        List<CredentialsAuthoritiesEntity> credentialsAuthoritiesEntityList = credentialsAuthoritiesMapper.selectList(new QueryWrapper<>(credentialsAuthoritiesEntityQuery));
        List<Long>  authoritiesIds = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(credentialsAuthoritiesEntityList)){
            for(CredentialsAuthoritiesEntity temp : credentialsAuthoritiesEntityList){
                authoritiesIds.add(temp.getAuthoritiesId());
            }
        }
        List<AuthorityEntity> authorityEntityList = null;
        if(CollectionUtils.isNotEmpty(authoritiesIds)){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("id",authoritiesIds);
            authorityEntityList = authorityMapper.selectList(queryWrapper);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(authorityEntityList)){
            for(AuthorityEntity authorityEntityTemp : authorityEntityList){
                log.info("用户["+credentialsEntity.getName()+"]密码["+credentialsEntity.getPassword()+"],角色["+authorityEntityTemp.getAuthority()+"]");
                authorities.add(new SimpleGrantedAuthority(authorityEntityTemp.getAuthority()));
            }
        }
        return new User(credentialsEntity.getName(), credentialsEntity.getPassword(), credentialsEntity.getEnabled(), true, true, true,authorities);
    }
}
